package com.btpj.module_search.ui

import android.os.Bundle
import androidx.paging.PageKeyedDataSource
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.btpj.jetpack.base.BaseListFragment
import com.btpj.jetpack.datasource.MutablePageKeyedDataSource
import com.btpj.jetpack.entity.DataBean
import com.btpj.module_search.adapter.SearchResultListAdapter
import com.scwang.smartrefresh.layout.api.RefreshLayout

class SearchResultFragment : BaseListFragment<DataBean, SearchResultViewModel>() {

    companion object {
        fun newInstance(hotKey: String) = SearchResultFragment().apply {
            arguments = Bundle().apply {
                putString("hotKey", hotKey)
            }
        }
    }

    override fun onCreateViewAfter() {
        super.onCreateViewAfter()
        hiddenActionBar()
        requireArguments().getString("hotKey")?.let { mViewModel.setHotKey(it) }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        val currentList = mAdapter.currentList
        if (currentList == null || currentList.size <= 0) {
            return
        }

        val count = currentList.size / 20
        mViewModel.loadDataAfter(count, object : PageKeyedDataSource.LoadCallback<Int, DataBean>() {
            override fun onResult(data: MutableList<DataBean>, adjacentPageKey: Int?) {
                val dataSource = MutablePageKeyedDataSource<DataBean>()
                dataSource.data.addAll(currentList)
                dataSource.data.addAll(data)
                mAdapter.submitList(dataSource.buildNewPageList(currentList.config))
            }
        })
        finishRefresh()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mViewModel.mDataSource!!.invalidate()
        finishRefresh()
    }

    @Suppress("UNCHECKED_CAST")
    override fun generateAdapter(): PagedListAdapter<DataBean, RecyclerView.ViewHolder> {
        return SearchResultListAdapter(requireContext()) as PagedListAdapter<DataBean, RecyclerView.ViewHolder>
    }

}